﻿@using Compass.Wasm.Shared.Files
@inject HttpClient Http

@if (string.IsNullOrEmpty(result))
{
    <span style="font-weight:bold;">@Title ：</span>
    if (!string.IsNullOrEmpty(FileUrl))
    {
        <FileLinkWithDelete FileUrl="@FileUrl" DeleteFile="DeleteFile"/>
    }
}
else
{
    <span>@result</span>
}
<InputFile class="form-control mb-2" OnChange="OnInputFileChange" accept="@FileType" />
@code {
    [Parameter]
    public string Title { get; set; }
    [Parameter]
    public string FileType { get; set; }

    [Parameter]
    public string FileUrl { get; set; }
    [Parameter]
    public EventCallback<string> FileUrlChanged { get; set; }
    //自定义组件实现双向绑定，https://blog.csdn.net/playermaker57/article/details/105443467
    
    Task DeleteFile(string file)
    {
        FileUrl = string.Empty;
        //双向绑定
        return FileUrlChanged.InvokeAsync(FileUrl);
    }

    public string result = string.Empty;

    private async Task OnInputFileChange(InputFileChangeEventArgs e)
    {
        var file = e.File;//一个文件
        using var content = new MultipartFormDataContent();
        content.Add(content: new StreamContent(file.OpenReadStream(1024 * 1024*100)),
            name: "\"files\"", fileName: file.Name);
        try
        {
            var response = await Http.PostAsync("api/Uploader", content);
            var uploadResponse = await response.Content
                .ReadFromJsonAsync<UploadResponse>();

            FileUrl = uploadResponse.RemoteUrl.ToString();
            //双向绑定
            await FileUrlChanged.InvokeAsync(FileUrl);
        }
        catch (Exception ex)
        {
            result =$"上传文件异常：{ex}";
        }
    }
}
